package cn.yuanqiao.manage.service.impl;

import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.manage.domain.YqFields;
import cn.yuanqiao.manage.domain.YqdaMdataList;
import cn.yuanqiao.manage.domain.YqdaMdataListShy;
import cn.yuanqiao.manage.domain.YqdaRelevance;
import cn.yuanqiao.manage.mapper.*;
import cn.yuanqiao.manage.service.IYqdaMdataListService;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 元数据明细Service业务层处理
 *
 * @author yuanqiao
 * @date 2023-06-09
 */
@Service
public class YqdaMdataListServiceImpl implements IYqdaMdataListService
{
    @Autowired
    private YqdaMdataListMapper yqdaMdataListMapper;
    @Autowired
    private HdListRelatedelementMapper relatedelementMapper;
    @Autowired
    private HdListSubelementMapper subelementMapper;
    @Autowired
    private YqFieldsMapper yqFieldsMapper;
    @Autowired
    private YqdaApplyModelMapper yqdaApplyModelMapper;

    /**
     * 查询元数据明细
     *
     * @param id 元数据明细主键
     * @return 元数据明细
     */
    @Override
    public YqdaMdataList selectYqdaMdataListById(Long id)
    {
        return yqdaMdataListMapper.selectYqdaMdataListById(id);
    }

    @Override
    public Map<String, Object> selectYqdaMdataListByIdAll(Long id) {
        Map<String, Object> map = new HashMap<>();
        map.put("HddaMDataList",yqdaMdataListMapper.selectYqdaMdataListById(id));
        map.put("HdListRelatedelement",relatedelementMapper.selectHdListRelatedelementByMListId(id));
        map.put("HdListSubelement",subelementMapper.selectHdListSubelementByMListId(id));
        return map;
    }

    /**
     * 查询元数据明细列表
     *
     * @param yqdaMdataList 元数据明细
     * @return 元数据明细
     */
    @Override
    public List<YqdaMdataList> selectYqdaMdataListList(YqdaMdataList yqdaMdataList)
    {
        return yqdaMdataListMapper.selectYqdaMdataListList(yqdaMdataList);
    }

    /**
     * 新增元数据明细
     * @return 结果
     */
    @Override
    @Transactional
    public int insertYqdaMdataList(String ids,Long groupId)
    {
        LoginUser user = SecurityUtils.getLoginUser();
        if(user == null){
            user = new LoginUser();
            user.setUserId(1L);
        }
        YqFields fields = new YqFields();
        fields.setIds(ids);
        List<YqFields> yqFieldsList = yqFieldsMapper.selectyqfieldsList(fields);
        for(YqFields data: yqFieldsList){
            //添加元数据明细
            YqdaMdataList mDataList = new YqdaMdataList();
            mDataList.setFieldCaption(data.getFieldCaption());
            mDataList.setGroupId(groupId);
            mDataList.setFieldName(data.getFieldName());
            mDataList.setFieldType(Integer.valueOf(data.getFieldType()));
            mDataList.setDataLength(Integer.valueOf(data.getFieldLength()));
            mDataList.setType(Integer.valueOf(data.getType()));
            mDataList.setShowType(Integer.valueOf(data.getShowType()));
            mDataList.setIsSystem(Integer.valueOf(data.getIsCommon()));

            mDataList.setDefaultValue(data.getDefaultVal());
            mDataList.setIsNoEmpty("true".equals(data.getNullable()) ? 0 : 1);

            //mDataList.setIsInput("true".equals(data.getNullAble()) ? 0 : 1);
            mDataList.setIsInput(0);
            mDataList.setIsUpdate(0);
            mDataList.setIsQuery(0);
            mDataList.setIsArchiveNo(0);
            // mDataList.setIsNoEmpty(0);
            mDataList.setIsHidden(1==Integer.valueOf(data.getShowModel())?0:1);
            mDataList.setIsExport(1);
            mDataList.setCheckChongfu(0);
            mDataList.setIsImport(0);
            mDataList.setIsMetadata(0);
            // mDataList.setShowType(4);
            mDataList.setZsfl("1");
            mDataList.setThWidth(StringUtils.isNotEmpty(data.getThWidth()) ? Integer.valueOf(data.getThWidth()):null);
            mDataList.setThAlign(data.getThAlign());
            mDataList.setCreatorId(user.getUserId());
            mDataList.setCreateTime(DateUtils.getNowDate());
            yqdaMdataListMapper.insertYqdaMdataList(mDataList);
        }
        return 1;
    }

    /**
     * 修改元数据明细
     *
     * @param yqdaMdataList 元数据明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateYqdaMdataList(YqdaMdataList yqdaMdataList, String ids)
    {
        //查询是否重复
        String [] idd = ids.split(",");
        if(idd.length == 1){
            YqdaMdataList select = new YqdaMdataList();
            select.setGroupId(yqdaMdataList.getGroupId());
            select.setType(yqdaMdataList.getType());
            select.setFieldCaption(yqdaMdataList.getFieldCaption());
            List<YqdaMdataList> mdataLists = yqdaMdataListMapper.selectYqdaMdataListListPrecise(select);
            if(mdataLists.size() > 0 && !idd[0].equals(String.valueOf(mdataLists.get(0).getId()))){
                throw new ServiceException("元数据明细中显示名称重复！");
            }
        }
        String changefiled=yqdaMdataList.getChangefiled();//获取修改的字段
        if("isInput".equals(changefiled)||"isUpdate".equals(changefiled)||"isHidden".equals(changefiled)||"isQuery".equals(changefiled)||"isExport".equals(changefiled)) {
            if(changefiled.toUpperCase().contains("QUERY")){//查询可能是精确查询到模糊查询类似,特殊处理
                if(0!=yqdaMdataList.getIsQuery()){

                }else{
                    searchandchangeapply(changefiled,yqdaMdataList.getGroupId(),yqdaMdataList.getType(),yqdaMdataList.getFieldName());
                }
            }else{
                searchandchangeapply(changefiled,yqdaMdataList.getGroupId(),yqdaMdataList.getType(),yqdaMdataList.getFieldName());
            }
        }

        return yqdaMdataListMapper.updateYqdaMdataList(yqdaMdataList,ids);
    }

    private void searchandchangeapply(String changefiled, Long groupId, Integer type,String field) {
        String realfield="";
        if("isInput".equals(changefiled)){
            if(0==type){
                realfield="JIANADDFIELD";
            }else if(1==type) {
                realfield = "JUANADDFIELD";
            }else if(2==type){
                realfield="EFILEADDFIELD";
            }else if(3==type){
                realfield="XIANGMUADDFIELD";
            }
        }else if("isUpdate".equals(changefiled)){
            if(0==type){
                realfield="JIANUPDATEFIELD";
            }else if(1==type) {
                realfield = "JUANUPDATEFIELD";
            }else if(2==type){
                realfield = "EFILEUPDATEFIELD";
            }else if(3==type){
                realfield="XIANGMUUPDATEFIELD";
            }
        }else if("isHidden".equals(changefiled)){
            if(0==type){
                realfield="JIANLISTFIELD";
            }else if(1==type) {
                realfield = "JUANLISTFIELD";
            }else if(2==type){
                realfield="EFILELISTFIELD";
            }else if(3==type){
                realfield="XIANGMULISTFIELD";
            }
        }else if("isQuery".equals(changefiled)){
            if(0==type){
                realfield="JIANQUERY";
            }else if(1==type) {
                realfield = "JUANQUERY";
            }else if(2==type){
                realfield="EFILEQUERY";
            }else if(3==type){
                realfield="XIANGMUQUERY";
            }
        }else if("isExport".equals(changefiled)){
            if(0==type){
                realfield="JIANEXPORTFIELD";
            }else if(1==type) {
                realfield = "JUANEXPORTFIELD";
            }else if(2==type){
                realfield="EFILEEXPORTFIELD";
            }else if(3==type){
                realfield="XIANGMUEXPORTFIELD";
            }
        }
        List<Map<String,Object>> applystringlist=yqdaApplyModelMapper.getstringforchange(groupId,realfield);
        if(null==applystringlist||applystringlist.size()==0){

        }else{
            for(Map applymap:applystringlist){
                boolean had=false;
                String applystring=(String)applymap.get(realfield);
                Long id=(Long)applymap.get("ID");
                if(applystring!=null){
                    String[] fields=applystring.split(",");
                    List<String> list=new ArrayList<>(fields.length);
                    for (int i = 0; i < fields.length; i++) {
                        if(field.equals(fields[i])){
                            had=true;
                        }else{
                            list.add(fields[i]);
                        }
                    }
                    if(had){
                        yqdaApplyModelMapper.updateYqdaApplyModelbygroupid(id,realfield,String.join(",",list));
                    }
                }

            }

        }

    }

    /**
     * 批量删除元数据明细
     *
     * @param ids 需要删除的元数据明细主键
     * @return 结果
     */
    @Override
    public int deleteYqdaMdataListByIds(Long[] ids)
    {
        //relatedelementMapper.deleteHdListRelatedelementByIds(ids);
        //subelementMapper.deleteHdListRelatedelementByIds(ids);
        return yqdaMdataListMapper.deleteYqdaMdataListByIds(ids);
    }

    /**
     * 删除元数据明细信息
     *
     * @param id 元数据明细主键
     * @return 结果
     */
    @Override
    public int deleteYqdaMdataListById(Long id)
    {
        return yqdaMdataListMapper.deleteYqdaMdataListById(id);
    }

    @Override
    public List<YqFields> getGroupDataList(YqFields yqfields, Long groupId) {
        return yqFieldsMapper.getGroupDataList(yqfields,groupId);
    }

    @Override
    public String copyIsRepeat(String ids, Long groupId,Integer type) {
        String msg = yqdaMdataListMapper.copyIsRepeat(ids,groupId,type);
        return msg;
    }

    @Override
    @Transactional
    public int copyToGroup(String ids, Long groupId, Integer type) {
        List<YqdaMdataList> dataLists = yqdaMdataListMapper.getDataListsByIds(ids);
        for(YqdaMdataList data:dataLists){
            YqdaMdataList num = yqdaMdataListMapper.isExist(data.getFieldName(),groupId,data.getType());
            if(num != null && type == 1){
                //覆盖
                data.setId(num.getId());
                data.setGroupId(groupId);
                yqdaMdataListMapper.updateYqdaMdataList(data, String.valueOf(data.getId()));
            }else if(num != null && type == 2){
                //跳过
                continue;
            }else {
                data.setId(null);
                data.setGroupId(groupId);
                yqdaMdataListMapper.insertYqdaMdataList(data);
            }
        }
        return 0;
    }

    @Override
    @Transactional
    public void importHddaMDataList(List<YqdaMdataList> dataLists, Long groupId, Integer type) {
        for(YqdaMdataList data:dataLists){
            YqdaMdataList num = yqdaMdataListMapper.isExist(data.getFieldName(),groupId,data.getType());
            if(num != null && type == 1){
                //覆盖
                data.setId(num.getId());
                data.setGroupId(groupId);
                yqdaMdataListMapper.updateYqdaMdataList(data, String.valueOf(data.getId()));
            }else if(num != null && type == 2){
                //跳过
                continue;
            }else {
                data.setId(null);
                data.setGroupId(groupId);
                data.setCreatorId(SecurityUtils.getUserId());
                data.setCreateBy(SecurityUtils.getUsername());
                data.setCreateTime(new Date());
                yqdaMdataListMapper.insertYqdaMdataList(data);
            }
        }
    }

    @Override
    public List<Map<String,Object>> selectYqdaMdataListListforshy(Long groupId,Integer type,String fieldCaption,String fieldName,Long categoryId) {
        return yqdaMdataListMapper.selectYqdaMdataListListforshy(groupId,type,fieldCaption,fieldName,categoryId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addmdatatoshy(JSONArray ids, Integer type, Long categoryId,Long groupId) {
        List<YqdaMdataList> dataListsByIds = yqdaMdataListMapper.getDataListsByIds(ids.toString().replace("[","").replace("]","").replace("\"",""));
        for (YqdaMdataList mdata:dataListsByIds) {
            Long id=yqdaMdataListMapper.selectshybyid(mdata.getId(),type,groupId,categoryId);
            YqdaMdataListShy yqdaMdataListShy=new YqdaMdataListShy();
            yqdaMdataListShy.setMdataId(mdata.getId());
            yqdaMdataListShy.setGroupId(groupId);
            yqdaMdataListShy.setType(type);
            yqdaMdataListShy.setFieldName(mdata.getFieldName());
            yqdaMdataListShy.setCategoryId(categoryId);
            yqdaMdataListShy.setId(SnowflakeIdGenerator.generateId());
            if (null==id){
                yqdaMdataListMapper.addmdatatoshy(yqdaMdataListShy);
            }else{
                //存储项都不会改变,不更新
                //yqdaMdataListShy.setId(id);
                //yqdaMdataListMapper.updatemdatatoshy(yqdaMdataListShy);
            }
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deletemdatafromshy(JSONArray ids, Integer type, Long categoryId, Long groupId) {
        for (int i = 0; i < ids.size(); i++) {
            YqdaMdataListShy yqdaMdataListShy=new YqdaMdataListShy();
            yqdaMdataListShy.setMdataId(ids.getLong(i));
            yqdaMdataListShy.setType(type);
            yqdaMdataListShy.setCategoryId(categoryId);
            yqdaMdataListShy.setGroupId(groupId);
            yqdaMdataListMapper.deletemdatafromshy(yqdaMdataListShy);
        }
        return 1;
    }

    @Override
    public List<Map<String, Object>> getrelevancefield(JSONObject json) {
        String field = json.getString("field");
        Integer nowlevel = json.getInteger("nowlevel");
        Integer relelevel = json.getInteger("relelevel");
        Integer fieldtype = json.getInteger("fieldtype");
        Long groupId = json.getLong("groupId");
        String noequals = "";
        if (relelevel == nowlevel) {
            noequals = " and FIELD_NAME!='" + field + "'";
        }
        return yqdaMdataListMapper.getrelevancefield(field, nowlevel, relelevel, fieldtype, groupId, noequals);
    }

    @Override
    public int addrelevance(JSONObject json) {
        String field = json.getString("field");
        String relefield = json.getString("relefield");
        Integer nowlevel = json.getInteger("nowlevel");
        Integer relelevel = json.getInteger("relelevel");
        Integer fieldtype = json.getInteger("fieldtype");
        Integer relefieldtype = json.getInteger("relefieldtype");
        Integer relation = json.getInteger("relation");
        Long groupId = json.getLong("groupId");
        YqdaRelevance relevance = new YqdaRelevance();
        relevance.setCreateDate(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        relevance.setCreator(SecurityUtils.getLoginUser().getUserId());
        relevance.setFieldName(field);
        relevance.setFieldType(fieldtype);
        relevance.setFieldLevel(nowlevel);
        relevance.setReleField(relefield);
        relevance.setRelefieldType(relefieldtype);
        relevance.setRelefieldLevel(relelevel);
        relevance.setGroupId(groupId);
        relevance.setRelation(relation);
        return yqdaMdataListMapper.addrelevance(relevance);
    }

    @Override
    public int editrele(YqdaRelevance relevance) {
        int i = yqdaMdataListMapper.gethadcount(relevance);
        if (i > 0) {
            throw new RuntimeException("和已有关联重复!修改失败");
        }
        relevance.setUpdater(SecurityUtils.getLoginUser().getUserId());
        relevance.setUpdateDate(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        return yqdaMdataListMapper.editrele(relevance);
    }

    @Override
    public int delterele(JSONObject json) {
        List ids = json.getJSONArray("ids");
        return yqdaMdataListMapper.delterele(ids);
    }

    @Override
    public YqdaRelevance getreledetail(Long id) {
        return yqdaMdataListMapper.getreledetail(id);
    }

    @Override
    public List<YqdaRelevance> getrelevancelist(JSONObject json) {
        YqdaRelevance relevance = new YqdaRelevance();
        relevance.setFieldName(json.getString("field"));
        relevance.setFieldLevel(json.getInteger("fieldlevel"));
        relevance.setFieldType(json.getInteger("fieldtype"));
        relevance.setGroupId(json.getLong("groupId"));
        return yqdaMdataListMapper.getrelevancelist(relevance);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUpdateYqdaMdataList(YqdaMdataList yqdaMdataList, String ids) {

            //查询是否重复
            String [] idd = ids.split(",");
//            if(idd.length == 1){
//                YqdaMdataList select = new YqdaMdataList();
//                select.setGroupId(yqdaMdataList.getGroupId());
//                select.setType(yqdaMdataList.getType());
//                select.setFieldCaption(yqdaMdataList.getFieldCaption());
//                List<YqdaMdataList> mdataLists = yqdaMdataListMapper.selectYqdaMdataListListPrecise(select);
//                if(mdataLists.size() > 0 && !idd[0].equals(String.valueOf(mdataLists.get(0).getId()))){
//                    throw new ServiceException("元数据明细中显示名称重复！");
//                }
//            }
            String changefiled=yqdaMdataList.getChangefiled();//获取修改的字段
            if("isInput".equals(changefiled)||"isUpdate".equals(changefiled)||"isHidden".equals(changefiled)||"isQuery".equals(changefiled)||"isExport".equals(changefiled)) {
                if(changefiled.toUpperCase().contains("QUERY")){//查询可能是精确查询到模糊查询类似,特殊处理
                    if(0!=yqdaMdataList.getIsQuery()){

                    }else{
                        searchandchangeapply(changefiled,yqdaMdataList.getGroupId(),yqdaMdataList.getType(),yqdaMdataList.getFieldName());
                    }
                }else{
                    searchandchangeapply(changefiled,yqdaMdataList.getGroupId(),yqdaMdataList.getType(),yqdaMdataList.getFieldName());
                }
            }

            return yqdaMdataListMapper.updateYqdaMdataList(yqdaMdataList,ids);
        }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean moveDown(Long metadataListIds, Long groupId, Long categoryId, Integer type) {
        boolean reutrnVal = true;
        StringBuilder moveDownSql = new StringBuilder();
        String orderNoString = yqdaMdataListMapper.getSingle("SELECT ORDER_NO FROM YQDA_MDATA_LIST WHERE ID="+metadataListIds);
        List<Map<String, String>> orderNoMapList = yqdaMdataListMapper.getListResult1("SELECT ID,ORDER_NO FROM YQDA_MDATA_LIST WHERE GROUP_ID="+groupId+" AND TYPE="+type+" ORDER BY ORDER_NO");
        String nextId = "";
        String nextOrderNo = "";
        for(int i=0;i<orderNoMapList.size();i++) {
            if (orderNoString!=null && orderNoMapList.get(i).get("ORDER_NO")!=null) {
                if (orderNoString.equals(orderNoMapList.get(i).get("ORDER_NO"))) {
                    nextId = orderNoMapList.get(i+1).get("ID");
                    nextOrderNo = orderNoMapList.get(i+1).get("ORDER_NO");
                    break;
                }
            }else {
                return reutrnVal;
            }
        }

        moveDownSql.append("UPDATE YQDA_MDATA_LIST SET ORDER_NO="+nextOrderNo+" WHERE ID="+metadataListIds+";UPDATE YQDA_MDATA_LIST SET ORDER_NO="+orderNoString+" WHERE ID="+nextId);
        yqdaMdataListMapper.excu(moveDownSql.toString());
        return reutrnVal;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean moveUp(Long metadataListIds, Long groupId, Long categoryId, Integer type) {
        boolean reutrnVal = true;
        StringBuilder moveUpSql = new StringBuilder();
        String orderNoString = yqdaMdataListMapper.getSingle("SELECT ORDER_NO FROM YQDA_MDATA_LIST WHERE ID="+metadataListIds);
        List<Map<String, String>> orderNoMapList = yqdaMdataListMapper.getListResult1("SELECT ID,ORDER_NO FROM YQDA_MDATA_LIST WHERE GROUP_ID="+groupId+" AND TYPE="+type+" ORDER BY ORDER_NO");
        String preId = "";
        String preOrderNo = "";
//			从数据库获取到的order_id是从1开始，所以i应该从1开始，若果为0，数据越界异常，且存在错位移动
//			for(int i=0;i<orderNoMapList.size();i++) {
        for(int i=1;i<=orderNoMapList.size();i++) {
            if (orderNoString!=null && orderNoMapList.get(i).get("ORDER_NO")!=null) {
                if (orderNoString.equals(orderNoMapList.get(i).get("ORDER_NO"))) {
                    preId = orderNoMapList.get(i-1).get("ID");
                    preOrderNo = orderNoMapList.get(i-1).get("ORDER_NO");
                    break;
                }
            }else {
                return reutrnVal;
            }
        }
        moveUpSql.append("UPDATE YQDA_MDATA_LIST SET ORDER_NO="+preOrderNo+" WHERE ID="+metadataListIds+";UPDATE YQDA_MDATA_LIST SET ORDER_NO="+orderNoString+" WHERE ID="+preId);
        yqdaMdataListMapper.excu(moveUpSql.toString());
        return reutrnVal;
    }

    @Override
    public List<YqdaMdataList> selectYqdaMdataListListforexport(Long groupId, Integer type, String fieldName, List ids) {
        return yqdaMdataListMapper.selectYqdaMdataListListforexport(groupId,type,fieldName,ids);
    }

}
